//累加ID分配器
class CumulationID {
    constructor(){
        this.minID = 0;
        this.maxID = 0;
        this.curID = 0;
        this.idCount = 0;
    }
    init(min = 1, max = 200000000)
	{
		if (min <= 0 || max <= 0 || min >= max)
		{
			return false;
		}
		this.minID = min;
		this.maxID = max;
		this.idCount = max - min + 1;
		this.curID = min - 1;
		return true;
    }
    reset()
	{
		if (this.idCount > 1)
		{
			this.curID = this.minID - 1;
		}
    }
    getID()
	{
		if (this.idCount > 1)
		{
			++this.curID;
			if (this.curID > this.maxID)
			{
				this.curID = this.minID;
			}
			return this.curID;
		}
		return 0;
	}
}
//重复ID分配器
class ReuseID {
    constructor(){
        this.minID = 0;
		this.maxID = 0;
		this.idCount = 0;
		this.idFree = null;
		this.idUse = new Set();
    }
    //必须>0
	init(min, max)
	{
		if (min <= 0 || max <= 0 || min >= max)
		{
			return false;
		}
		this.minID = min;
		this.maxID = max;
		this.idCount = max - min + 1;
		if (this.idCount > 0)
		{
            this.idFree = new Array(this.idCount);
			for (let i = 0; i < this.idCount; ++i)
			{
				this.idFree[i] = i+this.minID;
			}
			return true;
		}
		return false;
	}
	//重置
	reset()
	{
		this.idFree = new Array(this.idCount);
		this.idUse.clear();
		if (this.idCount > 0)
		{
			for (let i = 0; i < this.idCount; ++i)
			{
				this.idFree[i] = i+this.minID;
			}
		}
	}
	//获取一个ID，0表示失败
	attachID()
	{
		let id = 0;
		if (this.idCount > 0)
		{
			if (this.idFree.length>0)
			{
				id = this.idFree.shift();
				this.idUse.add(id);
			}
		}
		return id;
	}
	//回收一个ID
	detachID(id)
	{
		if (this.idCount > 0)
		{
			if (this.dUse.has(id))
			{
				this.idFree.push(id);
				this.idUse.delete(id);
				return true;
			}
		}
		return false;
	}
}

module.exports.CumulationID = CumulationID;
module.exports.ReuseID = ReuseID;